﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MetadataBasedConfig.EntityModel.Entity;
using MetadataBasedConfig.EntityModel;
using MetadataBasedConfig.Framework;
using System.Data.Objects;

namespace MetadataBasedConfig.EntityModel
{
    public static class ConfigurableObjectExtension
    {
        /// <summary>
        /// Load the configuration information of IConfigurable entity.
        /// Should used after linq query.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objectQuery"></param>
        /// <returns></returns>
        public static IEnumerable<T> LoadConfigInfoDatas<T>(this IEnumerable<T> objectQuery, MDAEntities entities)
            where T : ConfigurableEntityObject 
        {
            List<T> allEntities = objectQuery.ToList();
            allEntities.ForEach(t => t.ConfigMetaConfigInfoDatasLoader=entities.LoadConfigInfoDatas);
            return allEntities;
        }

        public static IEnumerable<T> LoadConfigInfoDatas<T>(this IEnumerable<T> objectQuery)
            where T : ConfigurableEntityObject
        {
            if (objectQuery is ObjectQuery<T>)
            {
                var objectQueryObj = objectQuery as ObjectQuery<T>;
                if (objectQueryObj != null && objectQueryObj.Context is MDAEntities)
                {
                    MDAEntities entities = objectQueryObj.Context as MDAEntities;
                    //foreach (var dd in objectQueryObj)
                    //{
                    //    dd.ConfigMetaConfigInfoDatasLoader = entities.LoadConfigInfoDatas;
                    //}
                    var alls = objectQueryObj.ToList();
                    alls.ForEach(t => t.ConfigMetaConfigInfoDatasLoader = entities.LoadConfigInfoDatas);
                    return alls;
                }
            }
            return objectQuery;
        }
    }
}
